﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace QunProject.Common
{
    /// <summary>
    /// Http/Cookie
    /// </summary>
    public static class HttpHelper
    {
        /// <summary>
        /// 模拟Post提交数据
        /// </summary>
        /// <param name="Url">请求地址</param>
        /// <param name="postDataStr">发送的数据</param>
        /// <returns></returns>
        public static string HttpPost(string Url, string postDataStr = "")
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(Url);
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            var data = Encoding.UTF8.GetBytes(postDataStr);
            httpWebRequest.ContentLength = data.Length;
            Stream requestStream = httpWebRequest.GetRequestStream();
            requestStream.Write(data, 0, data.Length);
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            Stream responseStream = httpWebResponse.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            string result = streamReader.ReadToEnd();
            streamReader.Close();
            responseStream.Close();
            return result;
        }

        /// <summary>
        /// 模拟Get请求
        /// </summary>
        /// <param name="Url">请求地址</param>
        /// <param name="postDataStr">发送的数据（格式为?key=value&key=value）</param>
        /// <returns></returns>
        public static string HttpGet(string Url, string postDataStr = "")
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(Url + ((postDataStr == "") ? "" : "?") + postDataStr);
            httpWebRequest.Method = "GET";
            httpWebRequest.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            Stream responseStream = httpWebResponse.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            string result = streamReader.ReadToEnd();
            streamReader.Close();
            responseStream.Close();
            return result;
        }

        /// <summary>
        /// 清除指定Cookie，不指定则清除所有cookie
        /// </summary>
        /// <param name="cookiename">cookie名称</param>
        public static void ClearCookie(string cookiename = "")
        {
            if (!string.IsNullOrWhiteSpace(cookiename))
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename];
                if (cookie != null)
                {
                    cookie.Expires = DateTime.Now.AddYears(-3);
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }
            }
            else
            {
                foreach (var item in HttpContext.Current.Request.Cookies.AllKeys)
                {
                    HttpCookie cookie = HttpContext.Current.Request.Cookies[item];
                    cookie.Expires = DateTime.Now.AddYears(-3);
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }
            }
        }
        /// <summary>
        /// 获取指定Cookie值
        /// </summary>
        /// <param name="cookiename">cookie名称</param>
        /// <returns></returns>
        public static string GetCookieValue(string cookiename)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename];
            string str = string.Empty;
            if (cookie != null)
            {
                str = cookie.Value;
            }
            return str;
        }
        /// <summary>
        /// 添加一个Cookie（24小时过期）
        /// </summary>
        /// <param name="cookiename">cookie名称</param>
        /// <param name="cookievalue">cookie值</param>
        /// <param name="outtime">过期时间（单位：小时）</param>
        public static void SetCookie(string cookiename, string cookievalue, int outtime = 24)
        {
            SetCookie(cookiename, cookievalue, DateTime.Now.AddHours(outtime));
        }
        /// <summary>
        /// 添加一个Cookie（24小时过期），指定域名
        /// </summary>
        /// <param name="cookiename">cookie名称</param>
        /// <param name="cookievalue">cookie值</param>        
        /// <param name="cookievalue">cookie值</param>
        /// <param name="outtime">过期时间（单位：小时）</param>
        public static void SetCookie(string cookiename, string cookievalue, string domian, int outtime = 24)
        {
            SetCookie(cookiename, cookievalue, DateTime.Now.AddHours(outtime), domian);
        }
        /// <summary>
        /// 添加一个Cookie
        /// </summary>
        /// <param name="cookiename">cookie名</param>
        /// <param name="cookievalue">cookie值</param>
        /// <param name="expires">过期时间 DateTime</param>
        /// <param name="domian">域名</param>
        public static void SetCookie(string cookiename, string cookievalue, DateTime expires, string domian = "")
        {
            HttpCookie cookie = new HttpCookie(cookiename)
            {
                Value = cookievalue,
                Expires = expires
            };
            if (!domian.IsNullOrWhiteSpace())
            {
                cookie.Domain = domian;
            }
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        /// <summary>
        /// 去除一段字符串中的HTML标签
        /// </summary>
        /// <param name="html">源HTML的字符串</param>
        /// <param name="length">截取摘要长度[0为不截取]</param>
        /// <param name="placeholder">占位符</param>
        /// <returns></returns>
        public static string ReplaceHtmlTag(string html, int length = 0, string placeholder = "...")
        {
            string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");
            strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");
            strText = strText.Replace(" ", "");
            strText = strText.Replace("\r\n", "");

            if (length > 0 && strText.Length > length)
            {
                return strText.Substring(0, length) + placeholder;
            }

            return strText;
        }
    }
}